<template>
  <el-main class="paper">
    <el-affix>
      <div class="header-container">
        <div class="header">
          <el-button text size="large" @click="handleSubmit">退出考试</el-button>
          <div class="center">
            {{ examInfo?.examName }}
            <div class="desc">（总分：{{ examInfo?.totalScore }}分，题数：{{ examInfo?.questionCount }} 道，时长：{{ examInfo.answerTime }} 分钟）</div>
          </div>
          <div class="right">
            <div v-if="examInfo?.examName">考试剩余：<common-time :exam-time="examInfo.surplusTime ? examInfo.surplusTime : examInfo.answerTime * 60" @callback="handleSubmitForTips" /></div>
            <el-button type="danger" size="large" @click="handleSubmit">立即交卷</el-button>
          </div>
        </div>
      </div>
    </el-affix>

    <div class="paper-container">
      <!--答题卡-->
      <el-affix :offset="85">
        <div class="paper-card">
          <paper-card :titles="examInfo.titles" @click="handleClickOption" />
        </div>
      </el-affix>
      <!--题目-->
      <div class="paper-question">
        <div v-for="(item, index) in examInfo.titles" :key="index">
          <div class="title">
            <div class="name">{{ item.titleName }}</div>
          </div>
          <div v-for="(itemSub, indexSub) in item.questions" :key="indexSub">
            <!--题目-->
            <paper-question :question="itemSub" :index="indexSub + 1" :record-id="examInfo.recordId" @update-answer="handleAnswer" />
          </div>
        </div>
      </div>
    </div>
  </el-main>
  <exam-countdown v-if="dialogVisible" :dialog-visible="dialogVisible" @callback="toReport" />
</template>
<script setup>
  import { examApi } from '~/api/exam'
  const route = useRoute()
  const examInfo = reactive({})
  const dialogVisible = ref(false)

  // 点击答题卡选项
  const handleClickOption = (index) => {
    if (document.getElementById(index)) {
      document.getElementById(index).scrollIntoView({ block: 'center', behavior: 'smooth' })
    }
  }

  // 答题处理
  const handleAnswer = (answer) => {
    examInfo.titles.forEach((item) => {
      item.questions.forEach((itemSub) => {
        if (itemSub.questionId === answer.questionId) {
          itemSub.userAnswer = answer.userAnswer
        }
      })
    })
  }

  // 手动交卷
  const handleSubmit = () => {
    ElMessageBox.confirm(checkAnswer(), '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      dialogVisible.value = true
      await examApi.examEnd({ recordId: examInfo.recordId })
    })
  }

  // 跳转考试报告
  const toReport = () => {
    dialogVisible.value = false
    useRouter().push({ name: 'exam-report', query: { id: route.query.id, recordId: examInfo.recordId } })
  }

  // 自动交卷（考试时间结束）
  const handleSubmitForTips = async (tips) => {
    const res = await examApi.examEnd({ recordId: examInfo.recordId })
    ElMessageBox.confirm(tips + '，系统已经自动交卷，请查看考试报告！', '提示', {
      confirmButtonText: '确定',
      showCancelButton: false,
      type: 'warning'
    })
      .then(() => {
        // 跳转考试报告
        useRouter().push({ name: 'exam-report', query: { id: route.query.id, recordId: examInfo.recordId } })
      })
      .catch(() => {
        useRouter().push({ name: 'exam-report', query: { id: route.query.id, recordId: examInfo.recordId } })
      })
  }

  /**
   * 切屏处理
   */
  let switchScreenInterval = null
  const handleSwitchScreen = async () => {
    if (!document.hasFocus()) {
      clearInterval(switchScreenInterval)
      // 记录切屏次数，返回剩余次数
      const res = await examApi.examSwitchScreen({ recordId: examInfo.recordId })
      if (res <= 0) {
        // 提示，并交卷
        await handleSubmitForTips('您切屏次数已超')
        return
      }

      await ElMessageBox.confirm('再离开 ' + res + ' 次页面后系统将自动交卷，请谨慎操作！', '切屏提示', {
        confirmButtonText: '知道了',
        showCancelButton: false,
        type: 'warning',
        center: true
      })
        .then(() => {
          switchScreenInterval = setInterval(() => {
            handleSwitchScreen()
          }, examInfo.switchScreenTime * 1000)
        })
        .catch(() => {
          switchScreenInterval = setInterval(() => {
            handleSwitchScreen()
          }, examInfo.switchScreenTime * 1000)
        })
    }
  }

  /**
   * 检查是否完成所有题目
   */
  function checkAnswer() {
    let tips = '确定要交卷吗？'
    examInfo.titles.forEach((item) => {
      item.questions.forEach((itemSub) => {
        if (!itemSub.userAnswer) {
          tips = '您还有未答试题，确定交卷吗？'
        }
      })
    })
    return tips
  }

  onMounted(async () => {
    let res
    // 先校验考试
    const checkRes = await examApi.examCheck({ examType: route.query.examType, relateId: route.query.id })
    if (checkRes.isExamination) {
      // 若考试中，继续考试
      res = await examApi.examContinue({ recordId: checkRes.recordId })
    } else {
      res = await examApi.examStart({ examType: route.query.examType, relateId: route.query.id })
    }
    Object.assign(examInfo, res)

    // 监听切屏
    if (examInfo.switchScreenLimit) {
      let tips = '特别提醒：本场考试已开启防作弊机制，切屏'
      if (examInfo.switchScreenCount > 0) {
        tips += ' ' + examInfo.switchScreenCount + ' 次页面'
      }
      tips += '后系统将自动交卷，答题过程中请勿切屏及刷新页面！'
      await ElMessageBox.confirm(tips, '温馨提示', {
        confirmButtonText: '我已知晓',
        showCancelButton: false,
        type: 'warning',
        center: true
      })

      switchScreenInterval = setInterval(() => {
        handleSwitchScreen()
      }, examInfo.switchScreenTime * 1000)
    }
  })

  onUnmounted(() => {
    if (switchScreenInterval) {
      clearInterval(switchScreenInterval)
    }
  })
</script>
<style lang="scss" scoped>
  .header-container {
    padding: 10px;
    border-bottom: 1px solid #dddddd;
    background-color: #fff;
    .header {
      display: flex;
      align-items: center;
      width: 1200px;
      margin: 0 auto;
      .center {
        display: flex;
        flex-direction: column;
        justify-content: center;
        width: 900px;
        font-size: 18px;
        text-align: center;
        .desc {
          color: #777;
          margin-top: 5px;
          font-size: 12px;
        }
      }
      .right {
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-size: 14px;
        width: 250px;
      }
    }
  }

  .paper-container {
    width: 1200px;
    margin: 20px auto;
    display: flex;
    .paper-card {
      width: 300px;
      margin-right: 20px;
      background-color: #fff;
      border-radius: 5px;
      padding: 20px;
      overflow: auto;
      height: calc(100vh - 155px);
    }
    .paper-question {
      flex: 1;
      font-size: 20px;
      //overflow: auto;
      .title {
        border-radius: 5px 5px 0 0;
        background-color: #fff;
        border-bottom: 1px solid #ddd;
        .name {
          padding: 20px;
        }
      }
    }
  }

  .paper {
    height: 100vh;
    margin: 0;
    padding: 0;
  }
</style>
